package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.exception.BaseException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 添加购物车
     * @param shoppingCartDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(ShoppingCartDTO shoppingCartDTO) {
        // 判断当前加入到购物车的商品是否已经存在
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
        // 设置userId为当前登录用户id
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);

        if(list != null && !list.isEmpty()) {
            // 如果已经存在了,只需要将数量+1
            shoppingCart = list.get(0);
            shoppingCart.setNumber(shoppingCart.getNumber() + 1);
            shoppingCartMapper.updateCartById(shoppingCart);
        }
        else {
            // 如果不存在，插入一条购物车数据
            Long dishId = shoppingCartDTO.getDishId();
            Long setmealId = shoppingCartDTO.getSetmealId();
            if (dishId != null) {// 菜品id不为空，该条记录是菜品数据
                // 查询菜品信息
                List<Dish> dishes = dishMapper.queryDishByIds(List.of(dishId));
                if (dishes == null || dishes.isEmpty()) {
                    throw new BaseException(MessageConstant.UNKNOWN_ERROR);
                }
                Dish dish = dishes.get(0);
                shoppingCart.setName(dish.getName());
                shoppingCart.setImage(dish.getImage());
                shoppingCart.setAmount(dish.getPrice());
            }else {
                // 不是菜品，就是套餐
                List<Setmeal> setmeals = setmealMapper.querysetmealByIds(List.of(setmealId));
                if (setmeals == null || setmeals.isEmpty()) {
                    // 空数据，抛异常
                    throw new BaseException(MessageConstant.UNKNOWN_ERROR);
                }
                Setmeal setmeal = setmeals.get(0);
                shoppingCart.setName(setmeal.getName());
                shoppingCart.setImage(setmeal.getImage());
                shoppingCart.setAmount(setmeal.getPrice());
            }
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setNumber(1);
            shoppingCartMapper.insert(shoppingCart);
        }
        log.info("新增数据成功:{}",shoppingCart);
    }

    /**
     * 当前用户查看购物车
     */
    @Override
    public List<ShoppingCart> getCurrentUserShorppingCartList() {
        ShoppingCart shoppingCart = ShoppingCart.builder().userId(BaseContext.getCurrentId()).build();
        return shoppingCartMapper.list(shoppingCart);
    }

    /**
     * 根据删除用户currentId的购物车数据
     * @param currentId
     */
    @Override
    public void clearShoppingCart(Long currentId) {
        shoppingCartMapper.clearShoppingCart(currentId);
    }

    /**
     * 当前用户购物车指定菜品数量减一
     * @param shoppingCartDTO
     */
    @Override
    public void subFromShoppintCart(ShoppingCartDTO shoppingCartDTO) {
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
        shoppingCart.setUserId(BaseContext.getCurrentId());

        // 去数据库查询当当前要修改的菜品的数据。
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if (list == null || list.isEmpty()) {
            throw new BaseException(MessageConstant.USER_DATA_ERROR);
        }
        ShoppingCart shoppingCartFromDataBase = list.get(0);
        // 设置id
        shoppingCart.setId(shoppingCartFromDataBase.getId());

        // 如果number已经为1了，继续减少将移除该商品
        if (shoppingCartFromDataBase.getNumber() == 1) {
            shoppingCartMapper.deleteDishOrSetmealById(shoppingCart);
            return;
        }
        // 设置数量
        shoppingCart.setNumber(shoppingCartFromDataBase.getNumber() - 1);
        shoppingCartMapper.updateCartById(shoppingCart);
    }



}
